using MediatR;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Entities;
using TerritoryGame.Domain.Repositories;
using TerritoryGame.Domain.ValueObjects;

namespace TerritoryGame.Application.Handlers.CommandHandlers;

public class PaintActionCommandHandler : IRequestHandler<PaintActionCommand, PaintActionResult>
{
    private readonly IGameRepository _gameRepository;
    private readonly IGameRoomRepository _roomRepository;
    
    public PaintActionCommandHandler(IGameRepository gameRepository, IGameRoomRepository roomRepository)
    {
        _gameRepository = gameRepository;
        _roomRepository = roomRepository;
    }
    
    public async Task<PaintActionResult> Handle(PaintActionCommand request, CancellationToken cancellationToken)
    {
        // 允许通过 GameId 或 RoomId 解析游戏
        Game? game = null;
        if (request.GameId != Guid.Empty)
        {
            game = await _gameRepository.GetByIdAsync(request.GameId);
        }
        if (game == null && request.RoomId.HasValue)
        {
            game = await _gameRepository.GetByRoomIdAsync(request.RoomId.Value);
        }
        if (game == null)
        {
            return new PaintActionResult
            {
                Success = false,
                ErrorMessage = "Game not found",
                Position = new Position(request.X, request.Y),
                BrushSize = request.BrushSize
            };
        }
        
        try
        {
            var position = new Position(request.X, request.Y);
            game.ProcessPaintAction(request.PlayerId, position, request.BrushSize);
            
            await _gameRepository.UpdateAsync(game);
            
            return new PaintActionResult
            {
                Success = true,
                Position = position,
                BrushSize = request.BrushSize
            };
        }
        catch (Exception ex)
        {
            return new PaintActionResult
            {
                Success = false,
                ErrorMessage = ex.Message,
                Position = new Position(request.X, request.Y),
                BrushSize = request.BrushSize
            };
        }
    }
}
